import { Icon } from 'antd';
import { Link } from 'react-router-dom'
import './index.less';

export class Head extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isLogin: false,
            user: ''
        }
        this.logout = this.logout.bind(this);
    }

    componentDidMount() {
        let getUserArr = window.sessionStorage.getItem("user");

        if (getUserArr != null) {
            getUserArr = JSON.parse(getUserArr);
            getUserArr.map(item => {
                if (item.status == true) {
                    this.setState({
                        isLogin: true,
                        user: item.name
                    });
                    // // 发送给购物车界面
                    // if (this.props.location.pathname == '/shoppingcar') {
                    //     this.props.getUser(item.name);
                    // }
                    return;
                }
            });
        }
    }

    logout() {
        // 退出时记录当前页面地址
        window.sessionStorage.setItem("backurl", this.props.location.pathname);

        // 设置登出状态
        let getUserArr = window.sessionStorage.getItem("user");

        getUserArr = JSON.parse(getUserArr);
        getUserArr.map(item => {
            if (item.name == this.state.user) {
                item.status = false;
                return;
            }
        });

        window.sessionStorage.setItem("user", JSON.stringify(getUserArr));
        this.setState({ isLogin: false });

        // 如果在购物车界面退出登录就要调回首页
        let path = this.props.location.pathname;
        if (path == '/shoppingcar') {
            this.props.history.replace('/');
        }
    }

    render() {
        let logInfo = this.state.isLogin == false ?
            (<p><Link to="/login">登录</Link><span>|</span><Link to="/register">注册</Link></p>) :
            (<p>欢迎您,<a href="javascript:;">{this.state.user}</a><span>|</span><a href="javascript:;" onClick={this.logout}>退出登录</a></p>);

        return (
            <div className="header w1000">
                <div className="header-l">
                    <Link to="/home">首页</Link>
                    <Link to="/goods">所有商品</Link>
                </div>
                <div className="header-r">
                    {logInfo}
                    <div className="cart">
                        <Link to='/shoppingcar' ><Icon type="shopping-cart" style={{ fontSize: 18, verticalAlign: 'middle', marginTop: -3, marginRight: 5, color: '#666' }} />购物车</Link>
                    </div>
                </div>
            </div>
        );
    }
}